#include "categorysettings.h"
#include "ui_categorysettings.h"
#include <QIcon>
#include "inquiresql.h"
#include <QDebug>
#include <QKeyEvent>
#include <QMessageBox>

CategorySettings::CategorySettings(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::CategorySettings)
{
    ui->setupUi(this);
    setWindowFlags(Qt::WindowStaysOnTopHint | Qt::ToolTip );
//    this->move((QApplication::desktop()->width() - this->width())/2,
//               (QApplication::desktop()->height() - this->height())/2);
//    this->setFixedSize(292,311);
    this->setFixedWidth(293);
    setWindowTitle(tr("   商品类别设置"));
    this->setLayout(ui->MainLayout);

    //设置自定义的鼠标指针图案
    QCursor *myCursor= new QCursor(QPixmap(":/Mouse/Image/mouse/mouse.png"),15,10);
    setCursor(*myCursor);

    m_sql = new InquireSql;
    lineEditCategoryPress = false;
    clearTreeWidgetCategory = false;
    isOnlyShowTreeWidget = false;

    ui->treeWidgetCategory->setHeaderHidden(true);
//    displayCategory();

    QWidget::installEventFilter(this);
}

CategorySettings::~CategorySettings()
{
    delete ui;
}

void CategorySettings::displayCategory()
{
    m_list.clear();
    clearTreeWidgetCategory = true;
    ui->treeWidgetCategory->clear();

    m_list = m_sql->InquireAttribute(categoryPage);

    QList<QTreeWidgetItem *> rootList;
    QTreeWidgetItem *allCategory = new QTreeWidgetItem;   //添加总类别
    allCategory->setText(0, tr("所有类别"));
    allCategory->setIcon(0, QIcon(":/Category/Image/category/all.png"));
    rootList.append(allCategory);
    ui->lineEditCategoryName->setText(allCategory->text(0));

    for(int i = 0; i < m_list.count(); ++i)
    {
        if (m_list.at(i).get_attribute_number().mid(4, 4) == "0000")
        {
            //该类别是父类别
            QTreeWidgetItem *fatherCategoryItem = new QTreeWidgetItem;   //添加父类别
            fatherCategoryItem->setText(0, m_list.at(i).get_attribute());
            fatherCategoryItem->setIcon(0, QIcon(":/Category/Image/category/father.png"));
            allCategory->addChild(fatherCategoryItem);
            displayChildCategory(fatherCategoryItem, m_list.at(i).get_attribute_number().mid(0, 4));
            continue;
        }
    }

    ui->treeWidgetCategory->insertTopLevelItems(0,rootList);  //将结点插入部件中
    ui->treeWidgetCategory->expandAll(); //全部展开
    ui->treeWidgetCategory->setCurrentItem(ui->treeWidgetCategory->itemAt(m_list.count() - 1 , 0));

    //设置按键
    ui->pushButtonDelete->setDisabled(true);
    ui->pushButtonModify->setDisabled(true);
    ui->pushButtonNew->setDisabled(false);
}

void CategorySettings::displayChildCategory(QTreeWidgetItem *&fatherCategoryItem,QString fatherCategpryNumber)
{
    for(int i = 0; i < m_list.count(); ++i)
    {
        if (m_list.at(i).get_attribute_number().mid(4, 4) == "0000")
            continue;
        if (m_list.at(i).get_attribute_number().mid(0, 4) == fatherCategpryNumber)
        {
            //该类别是子类别
            QTreeWidgetItem *childCategoryItem = new QTreeWidgetItem(fatherCategoryItem, QStringList(QString(m_list.at(i).get_attribute()))); //添加子节点
            childCategoryItem->setIcon(0, QIcon(":/Category/Image/category/child.png"));
            fatherCategoryItem->addChild(childCategoryItem);  //添加子类别
            continue;
        }
    }
}

void CategorySettings::keyPressEvent(QKeyEvent *ev)
{
    switch(ev->key())
    {
        case Qt::Key_Escape:
            this->hide();
            break;
    default:
        QWidget::keyPressEvent(ev);
    }
}

void CategorySettings::on_pushButtonNew_clicked()
{
    if (lineEditCategoryNameIsEmpty())
        return;

    if (categoryIsExist())
        return;

    //向数据库中插入类别
    QTreeWidgetItem *parent = ui->treeWidgetCategory->currentItem()->parent();
    if (parent == NULL)
    {
        //当前类别是所有类别
        int maxFatherCategoryNumber = 0;
        for(int i = 0; i < m_list.count(); ++i)
        {
            if (m_list.at(i).get_attribute_number().mid(4, 4) == "0000")
            {
                //该类别是父类别
                if (maxFatherCategoryNumber < m_list.at(i).get_attribute_number().mid(0, 4).toInt())
                    maxFatherCategoryNumber = m_list.at(i).get_attribute_number().mid(0, 4).toInt();
            }
        }
        maxFatherCategoryNumber++;

        CommodityAttribute categoryAttribute(QString::number(maxFatherCategoryNumber).rightJustified(4, '0')+"0000", ui->lineEditCategoryName->text());
        m_sql->InsertAttribute(categoryPage, categoryAttribute);
    }
    else
    {
        //当前类别是父类别
        int fatherCategoryNumber = -1;
        int maxChildCategoryNumber = 0;

        //寻找父类别号
        for(int i = 0; i < m_list.count(); ++i)
        {
            if (m_list.at(i).get_attribute() == (ui->treeWidgetCategory->currentItem()->text(0)))
            {
                fatherCategoryNumber = m_list.at(i).get_attribute_number().left(4).toInt();
                break;
            }
        }

        //寻找该父类别号下的子类别号的最大值
        for(int i = 0; i < m_list.count(); ++i)
        {
            if (m_list.at(i).get_attribute_number().left(4)
                    == QString::number(fatherCategoryNumber).rightJustified(4, '0'))
            {
                if (m_list.at(i).get_attribute_number().mid(4, 4) != "0000")
                {
                    //该类别是子类别
                    if (maxChildCategoryNumber < m_list.at(i).get_attribute_number().mid(4, 4).toInt())
                    {
                          maxChildCategoryNumber = m_list.at(i).get_attribute_number().mid(4, 4).toInt();
                    }
                }
            }
        }
        qDebug() << maxChildCategoryNumber;
        CommodityAttribute categoryAttribute(QString::number(fatherCategoryNumber).rightJustified(4, '0')
                                             + QString::number(++maxChildCategoryNumber).rightJustified(4, '0'),
                                             ui->lineEditCategoryName->text());
        m_sql->InsertAttribute(categoryPage, categoryAttribute);
    }
    displayCategory();    
}

//void CategorySettings::on_treeWidgetCategory_itemClicked(QTreeWidgetItem *item, int column)
//{
//    ui->lineEditCategoryName->setText(item->text(column));

//    QTreeWidgetItem *parent = item->parent();

//    if (parent == NULL)
//    {
//        //该类别是所有类别
//        ui->pushButtonDelete->setDisabled(true);
//        ui->pushButtonModify->setDisabled(true);
//        ui->pushButtonNew->setDisabled(false);
//        return;
//    }
//    if((parent->parent() == NULL))
//    {
//        //该类别是父类别
//        ui->pushButtonDelete->setDisabled(false);
//        ui->pushButtonModify->setDisabled(false);
//        ui->pushButtonNew->setDisabled(false);
//        return;
//    }
//    //该类别是子类别
//    ui->pushButtonNew->setDisabled(true);
//    ui->pushButtonDelete->setDisabled(false);
//    ui->pushButtonModify->setDisabled(false);
//}

bool CategorySettings::lineEditCategoryNameIsEmpty()
{
    if (ui->lineEditCategoryName->text().isEmpty())
    {
//        QMessageBox msgBox;
//        msgBox.setWindowTitle(tr("  ★温馨提示★"));
//        msgBox.setText(tr("请输入商品类别"));
//        msgBox.exec();

        QMessageBox::information(this, tr("(☆_☆)温馨提示 ..."),
                             tr("\n请输入商品类别"));
        return true;
    }
    return false;
}

bool CategorySettings::categoryIsExist()
{
    for(int i = 0; i < m_list.count(); ++i)
    {
        if ((ui->lineEditCategoryName->text() == m_list.at(i).get_attribute())
             || (ui->lineEditCategoryName->text() == tr("所有类别")))
        {
//            QMessageBox msgBox;
//            msgBox.setWindowTitle(tr("     ★温馨提示★"));
//            msgBox.setText(tr("此类别已存在,不需要重新设置"));
//            msgBox.exec();

            QMessageBox::information(this, tr("(☆_☆)温馨提示 ..."),
                                 tr("\n此类别已存在,不需要重新设置"));
            return true;
        }
    }
    return false;
}

void CategorySettings::onlyShowTreeWidget()
{
    lineEditCategoryPress = true;
    isOnlyShowTreeWidget = true;
    ui->labelCategoryName->hide();
    ui->lineEditCategoryName->hide();
    ui->pushButtonNew->hide();
    ui->pushButtonModify->hide();
    ui->pushButtonDelete->hide();
}

void CategorySettings::showAll()
{
    isOnlyShowTreeWidget = false;
    ui->labelCategoryName->show();
    ui->lineEditCategoryName->show();
    ui->pushButtonNew->show();
    ui->pushButtonModify->show();
    ui->pushButtonDelete->show();
    lineEditCategoryPress = false;
}

bool CategorySettings::eventFilter(QObject *, QEvent *event)
{
//    if(     (QEvent::WindowDeactivate == event->type()) )
//    {
//        if (isOnlyShowTreeWidget == true)
//            qDebug() << "true";
//        else
//            qDebug() << "false";
//    }

    if(     (QEvent::WindowDeactivate == event->type())
         && (isOnlyShowTreeWidget == true) )
    {
        this->hide();  //或者关闭窗口,加入自己的操作.
        return true ;
    }
    else
    {
        return false ;
    }
}

void CategorySettings::on_pushButtonDelete_clicked()
{
    QTreeWidgetItem *parent = ui->treeWidgetCategory->currentItem()->parent();

    //删除父类别以及所有子类别
    if ((parent != NULL) && (parent->parent() == NULL))
    {
        //寻找父类别号
        QString fatherCategoryNumber;
        for(int i = 0; i < m_list.count(); ++i)
        {
            if (m_list.at(i).get_attribute() == (ui->treeWidgetCategory->currentItem()->text(0)))
            {
                fatherCategoryNumber = m_list.at(i).get_attribute_number().left(4);
                break;
            }
        }
        //检查父类别(包括父类别本身)中是否有被使用的
        for(int i = 0; i < m_list.count(); ++i)
        {
            if (m_list.at(i).get_attribute_number().left(4) == fatherCategoryNumber)
            {
                if (m_sql->AttributeIsUsed(categoryPage, m_list.at(i).get_attribute_number()))
                {
                    QMessageBox::warning(this, tr("(☆_☆)温馨提示 ..."),
                                         tr("该类别已被使用,无法删除"));
                    return;
                }
            }
        }
        //删除父类别以及所有所属子类别
        for(int i = 0; i < m_list.count(); ++i)
        {
            if (m_list.at(i).get_attribute_number().left(4) == fatherCategoryNumber)
            {
                m_sql->DeleteAttribute(categoryPage, m_list.at(i).get_attribute_number());
            }
        }
    }
    //删除子类别
    else
    {
        for(int i = 0; i < m_list.count(); ++i)
        {
            if (m_list.at(i).get_attribute() == (ui->treeWidgetCategory->currentItem()->text(0)))
            {
                if (m_sql->AttributeIsUsed(categoryPage, m_list.at(i).get_attribute_number()))
                {
                    QMessageBox::warning(this, tr("(☆_☆)温馨提示 ..."),
                                         tr("该类别已被使用,无法删除"));
                    return;
                }
                m_sql->DeleteAttribute(categoryPage, m_list.at(i).get_attribute_number());
                break;
            }
        }
    }

    displayCategory();
}

void CategorySettings::on_pushButtonModify_clicked()
{
    if (lineEditCategoryNameIsEmpty())
        return;

    if (categoryIsExist())
        return;

    for(int i = 0; i < m_list.count(); ++i)
    {
        if (m_list.at(i).get_attribute() == (ui->treeWidgetCategory->currentItem()->text(0)))
        {
            CommodityAttribute categoryAttribute(m_list.at(i).get_attribute_number(),
                                                 ui->lineEditCategoryName->text());
            m_sql->UpdateAttribute(categoryPage, categoryAttribute);
            break;
        }
    }
    displayCategory();
}

void CategorySettings::on_treeWidgetCategory_itemDoubleClicked(QTreeWidgetItem *item, int column)
{
//    qDebug() << "on_treeWidgetCategory_itemDoubleClicked";
//    qDebug() << item->text(column);
    if (lineEditCategoryPress)
        emit displaycategory(item->text(column));
}

void CategorySettings::on_treeWidgetCategory_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *)
{
    if (clearTreeWidgetCategory)
    {
        clearTreeWidgetCategory = false;
        return;
    }

    ui->lineEditCategoryName->setText(current->text(0));

    QTreeWidgetItem *parent = current->parent();

    if (parent == NULL)
    {
        //该类别是所有类别
        ui->pushButtonDelete->setDisabled(true);
        ui->pushButtonModify->setDisabled(true);
        ui->pushButtonNew->setDisabled(false);
        return;
    }
    if((parent->parent() == NULL))
    {
        //该类别是父类别
        ui->pushButtonDelete->setDisabled(false);
        ui->pushButtonModify->setDisabled(false);
        ui->pushButtonNew->setDisabled(false);
        return;
    }
    //该类别是子类别
    ui->pushButtonNew->setDisabled(true);
    ui->pushButtonDelete->setDisabled(false);
    ui->pushButtonModify->setDisabled(false);
}
